package com.myopen.converter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.myopen.cachestatic.DicCacheStatic;

public class DicConverter<T> {

	public List<T> list;
	public Page<T> page;
	public String[] dicTypeKeys;//字段名称
	public String[] dicTypes;//字典名称，数量必须与dicTypeKeys一样
	
	public DicConverter(List<T> list,String[] dicTypeKeys,String[] dicTypes) { 
		this.list=list;
		this.dicTypeKeys=dicTypeKeys;
		this.dicTypes=dicTypes;
	}
	
	public DicConverter(Page<T> page,String[] dicTypeKeys,String[] dicTypes) {
		this.page=page;
		this.list=page.getList();
		this.dicTypeKeys=dicTypeKeys;
		this.dicTypes=dicTypes;
	}
	
	public List<T> getList() {
		for (int i=0;i<dicTypeKeys.length;i++) {
			for (T t : list) {
				Class<? extends Object> clazz=t.getClass();
				try {
					Method mGet=clazz.getMethod("getStr",String.class);
					try {
						String dicInfoCode=(String)mGet.invoke(t, dicTypeKeys[i]);
						if(!StrKit.isBlank(dicInfoCode)) {
							
							Record dicInfo=DicCacheStatic.getDicInfo(dicTypes[i], dicInfoCode);
							if(dicInfo==null) {
								dicInfo=new Record();
							}
							if(t instanceof Model<?>) {
								//如果是Model要使用put方法
								Method mPet=clazz.getMethod("put",String.class,Object.class);
								mPet.invoke(t, dicTypeKeys[i ]+"_dic",dicInfo.getStr("name"));
							}else {
								//如果是Record要使用set方法
								Method mSet=clazz.getMethod("set",String.class,Object.class);
								mSet.invoke(t, dicTypeKeys[i]+"_dic",dicInfo.getStr("name"));
							}
							
						}
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
					
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				}
			}
		}
		
		return list;
	}
	
	public Page<T> getPage(){
		List<T> list=getList();
		return new Page<>(list, page.getPageNumber(), page.getPageSize(), page.getTotalPage(), page.getTotalRow());
	}
}
